package ru.agiledev.akb.client.panel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import ru.agiledev.akb.client.*;
import ru.agiledev.akb.client.window.RegistrationWindow;
import ru.agiledev.akb.client.window.SendPasswordWindow;
import ru.agiledev.akb.shared.User;

/**
 * Created by a.kirillov
 * Date: 3/31/11 Time: 11:00 PM
 */
public class LoginPanel extends HorizontalPanel {

    private final AuthorizationServiceAsync authService = GWT.create(AuthorizationService.class);


    HorizontalPanel errorPanel = new HorizontalPanel();
    private RegistrationWindow registerWindow;
    private TextBox loginBox;
    private TextBox pwdBox;

    public LoginPanel(){
        setSpacing(3);
        setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);

        Label username = new Label("Имя пользователя");
        username.setStyleName("loginPanelText");
            Label password = new Label("Пароль");
        password.setStyleName("loginPanelText");

        loginBox = new TextBox();
            loginBox.setWidth("82px");
            loginBox.setHeight("10px");
        loginBox.setStyleName("loginPanelText");

        loginBox.addFocusHandler(new FocusHandler() {
            @Override
            public void onFocus(FocusEvent event) {
                if(errorPanel.isVisible()){
                    errorPanel.setVisible(false);
                }
            }
        });

        pwdBox = new PasswordTextBox();
            pwdBox.setWidth("82px");
            pwdBox.setHeight("10px");
        pwdBox.setStyleName("loginPanelText");
        pwdBox.addFocusHandler(new FocusHandler() {
            @Override
            public void onFocus(FocusEvent event) {
                if(errorPanel.isVisible()){
                    errorPanel.setVisible(false);
                }
            }
        });

        pwdBox.addKeyPressHandler(new KeyPressHandler() {
            public void onKeyPress(KeyPressEvent event) {
               if (event.getNativeEvent().getKeyCode() == 13) {
                    doLogin();
                }
            }
        });


        Button loginButton = new Button("Вход");
        loginButton.addClickHandler(new LoginClickHandler());
        loginButton.setStyleName("loginPanelText");
        add(errorPanel);

        errorPanel.setStyleName("loginErrorPanel");
        errorPanel.setVisible(false);
        errorPanel.setSpacing(4);

        add(username);
        add(loginBox);
        add(password);
        add(pwdBox);
        add(loginButton);



        VerticalPanel actions = new VerticalPanel();
        Anchor register = new Anchor("Зарегистрироваться");
        register.addClickHandler(new RegisterClickHandler());
        register.setStyleName("loginPanelText");

        Anchor forgot = new Anchor("Забыли пароль?");
        forgot.addClickHandler(new ForgotPasswordClickHandler());
        forgot.setStyleName("loginPanelText");

        actions.add(register);
        actions.add(forgot);


        add(actions);

    }

    protected void showLoginError(){
        HTML errorText = new HTML("Неверный логин или пароль");
        if((errorPanel.getWidgetCount() != 0)&&(errorPanel.getWidget(0)!=null)){
            errorPanel.remove(0);
        }
        errorPanel.add(errorText);
        errorPanel.setVisible(true);
    }

    protected void showServerError(){
        HTML errorText = new HTML("Ошибка сервера");
        if((errorPanel.getWidgetCount() != 0)&&(errorPanel.getWidget(0)!=null)){
            errorPanel.remove(0);
        }
        errorPanel.add(errorText);
        errorPanel.setVisible(true);
    }

    class LoginClickHandler implements  ClickHandler {
        @Override
        public void onClick(ClickEvent clickEvent) {
            doLogin();
    }
    }


    private void doLogin(){
        AsyncCallback callback = new AsyncCallback() {
            public void onSuccess(Object result) {
                User user = (User) result;
                if (user != null) {
                    AspectKnowledgeBaseApplication.get().setUser(user);
                } else {
                    showLoginError();
                }
            }

            public void onFailure(Throwable ex) {
                showServerError();

            }
        };
        //showLoading(true);
            authService.checkLogin(loginBox.getText(), pwdBox.getText(), callback);
        }

    class RegisterClickHandler implements ClickHandler {
        public void onClick(ClickEvent clickEvent) {
            registerWindow = new RegistrationWindow(RootPanel.get().getOffsetWidth()/2-325, RootPanel.get().getOffsetHeight()/2-325);
            registerWindow.show();

        }
    }

    class ForgotPasswordClickHandler implements ClickHandler {
        public void onClick(ClickEvent clickEvent) {
            SendPasswordWindow forgotPassword = new SendPasswordWindow(RootPanel.get().getOffsetWidth()/2-170, RootPanel.get().getOffsetHeight()/2-150);
            forgotPassword.show();
        }
    }

    public RegistrationWindow getRegisterWindow() {
        return registerWindow;
    }

    public void clear(){
        loginBox.setValue("");
        pwdBox.setValue("");
    }
}
